import { defineStore } from 'pinia'
import { ref } from 'vue'
import { useRouter } from 'vue-router'

interface SensorDataItem {
  id: string
  name: string
  value: number
  timestamp: string
}

interface CaptureData {
  picUrl: string
  captureTime: string
  quality: number
  sensorData: SensorDataItem[]
}

interface CaptureRecord {
  code: string
  msg: string
  data: CaptureData
}

interface CaptureResponse {
  code: number
  message: string
  data: CaptureRecord[]
}

export const useCameraStore = defineStore('camera', () => {
  const router = useRouter()
  const captures = ref<CaptureRecord[]>([])
  const loading = ref(false)
  const error = ref<string | null>(null)

  // 获取一周内的照片记录
  const fetchWeekCaptures = async () => {
    loading.value = true
    error.value = null
    console.log('开始获取照片记录...')

    try {
      // 检查token
      const token = localStorage.getItem('token')
      if (!token) {
        throw new Error('未登录')
      }

      const response = await fetch('http://localhost:8080/api/camera/captures/week', {
        method: 'GET',
        headers: {
          'Content-Type': 'application/json',
          'Accept': 'application/json',
          'Authorization': `Bearer ${token}`
        }
      })

      console.log('API响应状态:', response.status)
      
      if (response.status === 401 || response.status === 403) {
        localStorage.removeItem('token')
        localStorage.removeItem('isLogin')
        router.push('/login')
        throw new Error('登录已过期，请重新登录')
      }

      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`)
      }

      const result: CaptureResponse = await response.json()
      console.log('API响应数据:', result)
      
      if (result.code === 200 && result.data) {
        captures.value = result.data
        console.log('成功获取照片记录，数量:', captures.value.length)
      } else {
        throw new Error(result.message || '获取照片记录失败')
      }
    } catch (e) {
      console.error('获取照片记录错误:', e)
      error.value = e instanceof Error ? e.message : '获取照片记录失败'
      captures.value = []
    } finally {
      loading.value = false
    }
  }

  return {
    captures,
    loading,
    error,
    fetchWeekCaptures
  }
}) 